package org.mogu.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.mogu.Welcome;
import org.mogu.db.ActiveUserHelper;
import org.mogu.staticvalue.Convert;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class ImgLibSync {
	public ImgLibSync() {
		Log.e("init", "new ImgLibSync");
	}

	DefaultHttpClient client;
	HttpResponse httpResponse;
	HttpPost getResult = null;
	HttpGet getMethod = null;
	
	String imgurl=null;
	String infoallimglibupdatetime=null;
	int infoalltimeNum=0;
	String infoupdateimglibupdatetime=null;
	int infoupdatetimeNum=0;
	

	String updateTime;
	String lastUpdate;
	String appparam;
	String noticetitle;
	String noticecontent;
	String noticecode;

	String[] planurl;

	Date currentNow;
	int num = 0;

	boolean down = true;

	ProgressDialog dialog;

	List<NameValuePair> nameValuePair;

	SQLiteDatabase readdb = null;
	SQLiteDatabase wdb = null;
	InfoService context = null;
	Welcome welcome = null;
	ActiveUserHelper auh = null;
	boolean cdstatus = false;
	
	DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	// ArrayList<HttpGet> httpList=new ArrayList<HttpGet>();

	// private Handler handler = new Handler();
	Map<String, ArrayList<String>> appMap;
	Map<String, String> userAappMap = new HashMap<String, String>();

	public void syncw(Welcome contex, ActiveUserHelper au, String[] url) {
		this.welcome = contex;

		num = url.length;
		planurl = url;
		sync(null, au);

	}

	public int sync(InfoService contex, ActiveUserHelper au) {
		// infoallUrl = urls;
		Log.e("ImgLib", "1");
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			cdstatus = true;
		}
		this.context = contex;
		auh = au;

		int newcount = 0;
		try {
			synchronized (InfoSync.class) {
				if(readdb==null||!readdb.isOpen()){
					readdb = auh.getReadableDatabase();
				}
				

				Cursor activelist = readdb
						.rawQuery(
								"select username,password,writepwd,updateTime,lastUpdate,appparam from activeuser order by isactive desc",
								null);

				if (activelist.getCount() == 0) {
					activelist.close();
					Log.e("ImgLib", "2");
					// readdb.close();
					return 0;
				}
				activelist.moveToFirst();
//				uname = activelist.getString(0);
				if ("1".equals(activelist.getString(2))) {
//					pwd = activelist.getString(1);
					updateTime = activelist.getString(3);
					lastUpdate = activelist.getString(4);
					appparam = activelist.getString(5) == null ? ""
							: activelist.getString(5);
				} else {
					activelist.close();
					// wdb.close();
					Log.e("ImgLib", "3");
					return 0;
				}
				activelist.close();
				Cursor imgcursor = readdb
						.rawQuery(
								"select maincode from content where replyType='21'",
								null);
				String imglibcode=null;
				imgcursor.moveToFirst();
				while(!imgcursor.isAfterLast()){
					imglibcode=imgcursor.getString(0);
					break;
				}
				imgcursor.close();
				if(imglibcode==null){
					return 0;
				}
				String[] appAr = { Convert.uname ,imglibcode};
				Cursor app = readdb.rawQuery(
						"select url from app where username=? and code=?", appAr);
				imgurl=null;
				app.moveToFirst();
				while (!app.isAfterLast()) {
					imgurl=app.getString(0);
					break;
				}
				app.close();
				if (imgurl==null){
					return 0;
				}
				Cursor imglibcursor = readdb
						.rawQuery(
								"select infoupdateUpdateTime,infoupdateTimeNum from userapp where username=? and code=?",
								appAr);
				infoupdateimglibupdatetime=null;
				infoupdatetimeNum=0;
				imglibcursor.moveToFirst();
				while(!imglibcursor.isAfterLast()){
					infoupdateimglibupdatetime=imglibcursor.getString(0);
					infoupdatetimeNum=imglibcursor.getInt(1);
					break;
				}
				imglibcursor.close();
//				 readdb.close();
			}
			new Thread() {
				public void run() {
					String url;
					//Looper.prepare();
					if (planurl != null) {
						for (int m = 0; m < planurl.length; m++) {
							String[] u = planurl[m].split(",");
							url = "http://" + u[0] + "?UserName=" + Convert.uname
									+ "&UserPwd=" + Convert.upwd ;
//							if (u.length > 1) {
//								getAppParam(uname, u[1]);
//								url += userAappMap.get(uname + u[1]) == null ? ""
//										: userAappMap.get(uname + u[1]);
//							}

							// getMethod = new HttpGet(url + Convert.testNum);
							try {
							request(url);
							} catch (Exception e) {
								Log.e("imglibrequest", "main");
							}
						}
						planurl = null;

					} else {
						currentNow = new Date();
						try {
							if (infoupdateimglibupdatetime == null
									|| "".equals(infoupdateimglibupdatetime)
									|| (currentNow.getTime() - format1.parse(infoupdateimglibupdatetime).getTime())>= infoupdatetimeNum * 1000) {
								url = imgurl + "/InfoAllImg?UserName="
										+ Convert.uname + "&UserPwd=" + Convert.upwd;
							request(url);
								
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						
					}

				}
			}.start();
			// getResult = null;
			// getMethod = null;

		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());
			Log.e("DB", "InfoSync-220");

		}
		return newcount;
	}

	

	private void request(String uri) {
		Log.e("url", uri);
		HttpGet getMet = new HttpGet(uri + Convert.testNum);
		client = new DefaultHttpClient();
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
		try {
			httpResponse = client.execute(getMet);
			Log.e("request", "1");
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult;

				strResult = EntityUtils.toString(httpResponse.getEntity());
				Log.e("request", "2");
				if (!"1".equals(strResult)) {
					Log.e("request", "3");
					synchronized (InfoSync.class) {
						savecontnet(strResult, auh, 0);
					}
					Log.e("request", "4");
					
				}
			}
		}  catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());
			Log.e("request", uri);
		} finally {
			
		}

	}

	private int savecontnet(String strResult, ActiveUserHelper auh, int newcount){
		try {
			if(wdb==null||!wdb.isOpen()){
				wdb = auh.getReadableDatabase();
			}
			
		long t1 = System.currentTimeMillis();
		// 返回的xml
		

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = factory.newDocumentBuilder();
		Document document = db.parse(new java.io.ByteArrayInputStream(strResult
				.getBytes()));

		Element rootElement = document.getDocumentElement();
		long t2 = System.currentTimeMillis();
		String syncCode=null;
		String syncType=null;
		String syncTimespan=null;
		
		ContentValues activeuser = new ContentValues();
		syncCode = rootElement.getAttribute("code");
		String[] userappArg={Convert.uname,syncCode};
		 if (rootElement.hasAttribute("type")) {
			 syncType = rootElement.getAttribute("type");
			 syncTimespan = rootElement.getAttribute("timespan");
			 currentNow = new Date();
			 if("infoupdate".equals(syncType)){
				 activeuser.put("infoupdateTimeNum", syncTimespan);
				 activeuser.put("infoupdateUpdateTime", format1.format(currentNow));
				 
			 }
			 if("infoall".equals(syncType)){
				 activeuser.put("infoallTimeNum", syncTimespan);
				 activeuser.put("infoallUpdateTime", format1.format(currentNow));
			 }
			 
			 int num=wdb.update("userapp", activeuser, "username=? and code=?",
					 userappArg);
			 if(num==0){
				 activeuser.put("username", Convert.uname);
				 activeuser.put("code", syncCode);
				 wdb.insert("userapp", null, activeuser);
			 }
		 }

			readdb = auh.getReadableDatabase();
			String c = ",";
			String cr = ":";
			Cursor imglist = readdb.rawQuery(
					"select code,var from photoLib ", null);
			StringBuffer imagelist = new StringBuffer();
			imagelist.append(c);
			imglist.moveToFirst();
			while (!imglist.isAfterLast()) {
				imagelist.append(imglist.getString(0));
				imagelist.append(cr);
				imagelist.append(imglist.getString(1));
				imagelist.append(c);
				imglist.moveToNext();
			}
			imglist.close();
			String imageString=imagelist.toString();

			

			NodeList nodeList = rootElement.getElementsByTagName("lib");


			
			wdb.beginTransaction();

			InsertHelper ihimg = new InsertHelper(wdb, "photoLib");
			final int imgcode = ihimg.getColumnIndex("code");
			final int imglib = ihimg.getColumnIndex("lib");
			final int imggroup = ihimg.getColumnIndex("groupid");
			final int imgtype = ihimg.getColumnIndex("type");
			final int imgusername = ihimg.getColumnIndex("username");
			final int imgisDown = ihimg.getColumnIndex("isDown");
			final int imgappid = ihimg.getColumnIndex("appid");
			final int imgvar = ihimg.getColumnIndex("var");

			String imgcodestr="";
			String imglibstr;
			String imggroupstr;
			String imgappidstr=rootElement.getAttribute("codeid");;
			String imgvarstr;
			int isDown = 0;
			String imgtypedefault = ".jpg";
			
			String[] whereArgs=new String[2];
			whereArgs[1]= Convert.uname ;
			ContentValues photolib ;
			
				for (int i = 0; i < nodeList.getLength(); i++) {

					Element data = (Element) nodeList.item(i);
					imglibstr=data.getAttribute("name");
					NodeList groupList=data.getElementsByTagName("group");
					for(int j=0;j<groupList.getLength();j++){
						Element group = (Element) groupList.item(j);
						imggroupstr=group.getAttribute("name");
						NodeList imgList= group.getElementsByTagName("img");
						for(int k=0;k<imgList.getLength();k++){
							Element img = (Element) imgList.item(k);
							imgcodestr=img.getAttribute("id");
							imgvarstr=img.getAttribute("var");
							
							if (imageString.indexOf(c + imgcodestr + cr) == -1) {
								ihimg.prepareForInsert();
								ihimg.bind(imgcode, imgcodestr);
								ihimg.bind(imglib, imglibstr);
								ihimg.bind(imggroup, imggroupstr);
								ihimg.bind(imgtype, imgtypedefault);
								ihimg.bind(imgusername, Convert.uname);
								ihimg.bind(imgisDown, isDown);
								ihimg.bind(imgappid, imgappidstr);
								ihimg.bind(imgvar, imgvarstr);
								ihimg.execute();
								imageString += imgcodestr+cr+ imgvarstr+ c;
							}else if (imageString.indexOf(c + imgcodestr + cr+imgvarstr+c) == -1) {
								photolib=new ContentValues();
								photolib.put("var", imgvarstr);
								photolib.put("isDown", 0);
								whereArgs[0] = imgcodestr;
								wdb.update("photoLib", photolib, "code=? and username=?",
										whereArgs);
							}
							
						}
					}
				}
			

			wdb.setTransactionSuccessful();

		long t3 = System.currentTimeMillis();
		Log.i("One time", String.valueOf(t2 - t1));
		Log.i("Two time", String.valueOf(t3 - t2));
		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());
			Log.e("DB", "InfoSync-438");

		} finally {
			// wdb.setLockingEnabled(true );
			wdb.endTransaction();
		}
		
		return newcount;
	}

	
}
